#coding=utf-8
import datetime
from elixir import *
from gui_session import gui_session

from stockdb.misc import find_stock

class StGroup(Entity):
    using_options(tablename='stgroups')
    
    name = Field(String(20))
    created_at = Field(Date , default=datetime.date.today)
    note = Field(Text)

    stocks = ManyToMany('MyStock')
    
    def __init__(self, name=None):
        if name:
            self.name = name
            
    def get_codes(self):    
        return [ s.code for s in self.stocks ]
        
    def add_stocks(self, *codes ):
        
        for c in codes:
            #print c
            s = find_stock(c)
            self.stocks.append( MyStock(c, s.name))
            
        gui_session.flush()
        
    def remove_stock(self, code):
    
        s = MyStock.query.filter_by(code=code).one()
        for pp in s.pps:
            pp.delete()
        s.delete()
        
        gui_session.flush()  

    
    def get_mystock(self, code):
    
        for s in self.stocks:
            if s.code == code:
                return s
                        
        return None
                                        
class MyStock(Entity):
    using_options(tablename='mystocks')
    
    code = Field(String(6), required=True)    
    name = Field(String(20), required=True)
    
    stgroups = ManyToMany('StGroup')
    pps = OneToMany('PricePoint')
    
    def __init__(self, code, name):
        self.code = code
        self.name = name
        
    def add_pps(self, *vs):
        for v in vs:
            self.pps.append(PricePoint(v))
        
        gui_session.flush()
    
    def remove_pps(self):
        for pp in self.pps:
            pp.delete()
            
        gui_session.flush()
    
    def remove_pp(self, value):
    
        p = PricePoint.query.\
                filter_by(stock=self).\
                filter_by(value=value).one()
        
        p.delete()
        
        gui_session.flush()
        
class PricePoint(Entity):
    using_options(tablename='pricepoints')
    
    value = Field(Float, required=True)
    
    stock = ManyToOne('MyStock')

    def __init__(self, value):
        self.value = value
